package com.hmy.contract.job.contract;

import cn.hutool.core.collection.CollUtil;
import com.hmy.contract.service.contract.IContractService;
import com.hmy.contract.service.contract.ISupplyContractService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author seven.qi 齐胜南
 * @version 1.0
 * @description
 * @date 2024/1/26 13:35
 */
@Slf4j
@Component
public class ContractCreateJobHandler {

    @Resource
    private IContractService contractService;

    @Resource
    private ISupplyContractService supplyContractService;

    @Value("${contract.job.collect.count:1}")
    private Long collectCount;


    @XxlJob("contractCreateJobHandler")
    public void contractCreateHandler() {
        log.info("begin execute contractCreateJobHandler");
        List<Long> idList = contractService.getWaitingCreateContract(collectCount);
        if (CollUtil.isEmpty(idList)) {
            log.info("collect contractId list empty");
            return;
        }
        log.info("collect contractId size : {} list : {}", idList.size(), idList);
        for (Long id : idList) {
            log.info("begin create contract, id : {}", id);
            try {
                contractService.contractCreate(id);
            } catch (Exception e) {
                log.error("contract id : {} create failed", id, e);
                contractService.updateContractStatusFailed(id);
                log.error("contract id : {} update status failed", id);
            }
            log.info("end create contract, id : {}", id);
        }

    }

    @XxlJob("supplyContractCreateJobHandler")
    public void supplyContractCreateJobHandler() {
        log.info("begin execute supplyContractCreateJobHandler");
        List<Long> idList = supplyContractService.getWaitingCreateSupplyContract(collectCount);
        if (CollUtil.isEmpty(idList)) {
            log.info("collect supplyContractId list empty");
            return;
        }
        log.info("collect supplyContractId size : {} list : {}", idList.size(), idList);
        for (Long id : idList) {
            log.info("begin create supply contract, id : {}", id);
            try {
                supplyContractService.createSupplyContract(id);
            } catch (Exception e) {
                log.error("supplyContract id : {} create failed", id, e);
                supplyContractService.updateSupplyContractStatusFailed(id);
                log.error("supplyContract id : {} update status failed", id);
            }
            log.info("end create contract, id : {}", id);
        }

    }

}
